package com.qltv.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qltv.pojo.SNSUserInfo;
import com.qltv.pojo.WeixinOauth2Token;
import com.qltv.utils.AdvancedUtil;

public class OauthServlet extends HttpServlet {

	private static final long serialVersionUID = 6025275561783807096L;
	//订阅号无法开通网页授权接口，我擦了，只有服务号微信认证后才能开通，这个暂时先用不了。
	//回头试试这个好像可以 第二步：通过code换取网页授权access_token
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//用户同意授权后，能得到code
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		
		if(!"authdeny".equals(code)){
			//获取网页授权access_token
			WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("wx314b84ea36660a09", "98ee5ea48ec9f8763792ab1c0bbe5576", code);
			//网页授权接口访问凭证
			String accessToken = weixinOauth2Token.getAccessToken();
			String openId = weixinOauth2Token.getOpenId();
			//获取用户信息
			SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
			
			//设置要传递的参数
			request.setAttribute("snsUserInfo", snsUserInfo);
			request.setAttribute("state", state);
		}
		//跳转到index.jsp
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

}
